import { useEffect, useState, useRef } from "react";
import ProForm, {
  ProFormText,
  ProFormSelect,
  ProFormDigit,
  ProFormList,
} from "@ant-design/pro-form";
import ProCard from "@ant-design/pro-card";
import { message } from "antd";
import { LeftOutlined } from "@ant-design/icons";

import UploadFile from "@/components/UploadFile";
import { packageTypeOptions } from "@/const";
import EditableLabels from "@/components/EditableLabels";
import { add, update, fetchInfo } from "@/api/agreement";
import { PageContainer, FooterToolbar } from "@ant-design/pro-layout";
import { useLocation, history } from "umi";
import Editor from "@/components/Editor";

export default () => {
  const location = useLocation();
  const { id } = location.query;
  const title = id ? "编辑协议" : "新增协议";
  const formRef = useRef();
  const [info, setInfo] = useState({});

  const getInfo = async () => {
    const res = await fetchInfo({ id });
    if (res.code == 200) {
      const postData = {
        ...res.data,
      };
      setInfo(postData);
      formRef.current.setFieldsValue(postData);
    }
  };

  useEffect(() => {
    if (id) {
      getInfo();
    }
  }, []);

  const handleAddOrUpdate = async (fields) => {
    const postData = {
      ...fields,
      id: id,
    };
    const res = await update(postData);
    if (res.code == 200) {
      message.success(title + "成功");
      history.goBack();
    }
  };

  return (
    <PageContainer
      header={{
        title: (
          <div className="pointer" onClick={() => history.goBack()}>
            <LeftOutlined style={{ marginRight: 10 }} />
            {title}
          </div>
        ),
        breadcrumb: {},
      }}
    >
      <ProForm
        layout="horizontal"
        formRef={formRef}
        onFinish={async (values) => {
          return handleAddOrUpdate(values);
        }}
        submitter={{
          render: (_, dom) => <FooterToolbar>{dom}</FooterToolbar>,
        }}
      >
        <ProCard title={info.name} bordered>
          <ProForm.Item label="" name="content">
            <Editor />
          </ProForm.Item>
        </ProCard>
      </ProForm>
    </PageContainer>
  );
};
